#include "Bullet.hpp"
#include <cmath>

sf::Texture Bullet::bulletTexture;
bool Bullet::textureLoaded = false;

void Bullet::loadTexture() {
    if (!textureLoaded) {
        if (!bulletTexture.loadFromFile("resources/textures/bullet.png")) {
            throw std::runtime_error("Failed to load bullet texture");
        }
        textureLoaded = true;
    }
}

Bullet::Bullet(const sf::Vector2f& position, float rotation) {
    loadTexture();
    
    mSprite.setTexture(bulletTexture);
    mSprite.setOrigin(SIZE / 2.f, SIZE / 2.f);
    mSprite.setPosition(position);
    mSprite.setRotation(rotation);
    
    // 计算子弹速度向量
    float angle = rotation * M_PI / 180.f;
    mVelocity = sf::Vector2f(std::sin(angle) * SPEED,
                             -std::cos(angle) * SPEED);
    
    // 启动生命周期计时器
    mLifetimeClock.restart();
}

void Bullet::update(sf::Time deltaTime) {
    // 更新子弹位置
    mSprite.move(mVelocity * deltaTime.asSeconds());
}

void Bullet::render(sf::RenderWindow& window) {
    window.draw(mSprite);
}

bool Bullet::isOutOfBounds() const {
    sf::Vector2f pos = mSprite.getPosition();
    return pos.x < 0 || pos.x > 800 ||  // 假设屏幕宽度为800
           pos.y < 0 || pos.y > 600;    // 假设屏幕高度为600
}

sf::FloatRect Bullet::getBounds() const {
    return mSprite.getGlobalBounds();
}